此篇繼續介紹更多陣列的用法。
將指定範圍的陣列修改。
originarray:["one","two","three","four","five","six"],
exex:[],
("change", 2,5),change表示要替換的值,2和5表示範圍,2為該陣列的第3筆,5為第5筆。
this.exex= this.originarray.fill("change", 2,5)
console.log(this.exex)//輸出["one", "two", "change", "change", "change", "six"]
刪除陣列裡指定範圍的元素再新增。
originarray:["one","two","three","four","five","six","seven"],
(4, 2,"nor","test","math"):從索引值4的地方(第五筆),刪除2筆值,並新增"nor","test","math"這三個字串到陣列裡。
this.originarray.splice(4, 2,"nor","test","math");
console.log(this.originarray)
//輸出[ "one", "two", "three", "four", "nor", "test", "math", "seven" ]
移除該陣列最後一筆值。
originarray:["one","two","three","four","five","six","seven"],
exex:null,
this.exex = this.originarray.pop()
console.log(this.exex)
//輸出seven
console.log(this.originarray)
//輸出["one", "two", "three", "four", "five", "six"]
移除該陣列第一筆值。
originarray:["one","two","three","four","five","six","seven"],
exex:null,
this.exex = this.originarray.shift()
console.log(this.exex)
//輸出one
console.log(this.originarray)
//輸出["two", "three", "four", "five", "six", "seven"]
將兩個陣列合併。
arraytest:["new"],
bigarray:[],
originarray:["one","two","three","four","five","six","seven"],
this.originarray.concat(this.arraytest):將arraytest這個陣列合併到originarray陣列。
this.bigarray = this.originarray.concat(this.arraytest)
console.log(this.bigarray)
//輸出["one", "two", "three", "four", "five", "six", "seven", "new"]
合併該陣列和轉字串。
originarray:["one","two","three","four","five","six","seven"],
exex:null,
this.exex = this.originarray.join()
console.log(typeof(this.exex)
//輸出string
console.log(this.exex)
//one,two,three,four,five,six,seven
也可以在括號裡面輸入字串,改變陣列之間連接的值。
this.exex = this.originarray.join("----")
console.log(typeof(this.exex))
//輸出string
console.log(this.exex)
//輸出one----two----three----four----five----six----seven
擷取指定範圍的陣列之值。
originarray:["one","two","three","four","five","six","seven"],
exex:null,
slice(1, 5):抓取該陣列索引值1到4(不包括索引值5的值)。
this.exex = this.originarray.slice(1, 5)
console.log(this.exex)
//輸出["two", "three", "four", "five"]
排序陣列(只排第一個字元,若相同則比較第二個)。
originarray:["one","two","three","four","five","six","seven"],
numarray:[87,62,456,70,9,7,8456,39,563],
this.numarray.sort()
this.originarray.sort()
console.log(this.numarray)
//輸出[39, 456, 563, 62, 7, 70, 8456, 87, 9]
console.log(this.originarray)
//輸出["five", "four", "one", "seven", "six", "three", "two"]